// tslint:disable
import { Component, OnInit, Input } from "@angular/core";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { Router } from "@angular/router";

import { JPush } from "@jiguang-ionic/jpush/ngx";

import * as CryptoJS from 'crypto-js';

import { EventService } from "src/app/shared/service/event.service";

import { CustomValidators } from "../../shared/custom-validators/custom-validators";
import { AppGlobalService } from "../../shared/service/app-global.service";
import { HttpService } from "../../shared/service/http.service";
import { ChatService } from "../../shared/service/chatService";
import { IndexedDBService } from "../../shared/service/indexed-db.service";
import { MapBaiduService } from '../../shared/service/map.baiduapi';
import { ProcessLoginDataService } from '../../shared/service/process-login-data.service';
import { MessageService } from "../../shared/service/message.service";
import { ViewChild } from '@angular/core';
import { ModalController, Platform } from '@ionic/angular';
import { PageModalService } from "src/app/shared/service/page-modal-service";
import { ShareService } from "src/app/shared/service/share.service";
declare const Umeng;
@Component({
  selector: 'app-one-click-login',
  templateUrl: './one-click-login.component.html',
  styleUrls: ['./one-click-login.component.scss'],
})
export class OneClickLoginComponent implements OnInit {
  loginForm: FormGroup;
  registerForm: FormGroup;
  registerForm2: FormGroup;
  open: boolean;
  accountNum = '';
  passwordNum = '';
  messages: any;
  appTypeCustom: any;
  disableBtn = false;
  isCheckRead = false;
  isNeedGetBadgeAfterSubmit = false;
  // 左上角按钮
  topLeftBtn: any;
  // 右上角按钮
  topRightBtn: any;
  // 中间第一个按钮
  centerFirstBtn: any;
  // 中间第二个按钮
  centerSecondBtn: any;

  time = -1;
  text = "获取验证码";

  @ViewChild('accountInput') accountInput;
  @ViewChild('passwordInput') passwordInput;

  titleCssStyle: any;// 标题样式
  tipsCssStyle: any;// tips样式
  layoutBelowPrivacy: any;// 按钮布局
  buttonCssStyle: any;// 按钮样式
  buttonLabelCssStyle: any;// 按钮样式
  isHiddenSwitchIcon: any;// 是否隐藏按钮
  vCodeCssStyle: any;// 验证码文字样式
  titleCloseIconCssStyle: any;// 新增关闭按钮样式


  @Input() tagData: any = {};
  sessionId: string;
  mvcode: any;
  constructor(
    private platform: Platform,
    private eventService: EventService,
    private modalCtrl: ModalController,
    private fb: FormBuilder,
    private http: HttpService,
    private appGlobalService: AppGlobalService,
    private shareService: ShareService,
    private pageModalService: PageModalService,
    private processLoginData: ProcessLoginDataService,
    private indexedDBService: IndexedDBService,
    private mapBaiduService: MapBaiduService,
    private message: MessageService,
    private webSocketTalk: ChatService,
    private jPush: JPush,
    public router: Router
  ) {
  }
  ngOnInit() {
    const that = this;
    const bodyStyles = window.getComputedStyle(document.body);
    this.sessionId = localStorage.getItem("sessionId");
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    const parttern = "[A-Za-z0-9]{6,12}";

    // console.log('ngOnInit---:', this.tagData); 

    if (localStorage.getItem('client') !== 'APP') {
      this.tagData.wxLink = null;// 2.1.0 蜂喔用户授权登录;
    }


    // 手机号码登录
    if (this.tagData.style === 'mobileLogin') {
      this.registerForm = this.fb.group({
        account: [
          "",
          [
            Validators.required,
            Validators.minLength(11),
            Validators.maxLength(11),
            CustomValidators.phone
          ]
        ],
        mvcode: ["", [Validators.required, CustomValidators.vcode]],
      });
      //密码登录
    } else {
      this.registerForm2 = this.fb.group({
        account: [
          "",
          [
            Validators.required,
            Validators.minLength(11),
            Validators.maxLength(11),
            CustomValidators.phone
          ]
        ],
        password: [
          "",
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(12),
            Validators.pattern(parttern)
          ]
        ]
      });
    }

    let mobile =
      localStorage.getItem("loginAccount") &&
        localStorage.getItem("loginAccount") !== "undefined"
        ? localStorage.getItem("loginAccount")
        : "";
    if (mobile && mobile.length > 11) {
      mobile = '';
    }
    // const parttern = "[A-Za-z0-9]{6,12}";



    // 登录弹窗标题栏新增样式配置参数
    if (this.tagData.button && this.tagData.button.actionElement && this.tagData.button.actionElement.param) {
      const params = this.tagData.button.actionElement.param;
      params.forEach(element => {
        if (element.name === "titleCssStyle") {
          this.titleCssStyle = element.value;
        } else if (element.name === "tipsCssStyle") {
          this.tipsCssStyle = element.value;
        } else if (element.name === "layoutBelowPrivacy") {
          this.layoutBelowPrivacy = element.value;
        } else if (element.name === "buttonCssStyle") { // 按钮盒子样式
          this.buttonCssStyle = element.value;
        } else if (element.name === "buttonLabelCssStyle") { // 按钮盒子样式
          this.buttonLabelCssStyle = element.value;
        } else if (element.name === "isHiddenSwitchIcon") {
          this.isHiddenSwitchIcon = element.value;
        } else if (element.name === "vCodeCssStyle") {
          this.vCodeCssStyle = element.value;
        } else if (element.name === "titleCloseIconCssStyle") { // 蜂喔 1.9.19 新增关闭按钮样式
          this.titleCloseIconCssStyle = element.value;
        }
      });
    }
    this.accountNum = mobile;

    setTimeout(() => {
      this.focusInput('1'); // 自动获取焦点  
    }, 200);
    
  }

  register() {
    const register = this.tagData.register;
    const params = {
      pageId: register.link.target,
      params: {},
      sessionId: localStorage.getItem("sessionId")
    };
    this.appGlobalService.goToForward(params);
  }

  changePwd() {
    const forget = this.tagData.forget;
    const params = {
      pageId: forget.link.target,
      params: {},
      sessionId: localStorage.getItem("sessionId")
    };
    localStorage.setItem("loginAccount", this.loginForm.value.account);
    this.appGlobalService.goToForward(params);
  }

  getErrors() {

    if (this.tagData.style === 'mobileLogin') {
      if (this.registerForm.controls.account.errors) {
        if (this.registerForm.controls.account.errors.required) {
          this.appGlobalService.showToast("请输入手机号码", 3000, "top");
        } else {
          this.appGlobalService.showToast("请输入正确的手机号码", 3000, "top");
        }
      }
    } else {
      if (this.registerForm2.controls.account.errors) {
        if (this.registerForm2.controls.account.errors.required) {
          this.appGlobalService.showToast("请输入手机号码", 3000, "top");
        } else {
          this.appGlobalService.showToast("请输入正确的手机号码", 3000, "top");
        }
      } else if (this.registerForm2.controls.password.errors) {
        if (this.registerForm2.controls.password.errors.required) {
          this.appGlobalService.showToast("请输入密码", 3000, "top");
        } else {
          this.appGlobalService.showToast("请输入正确的密码", 3000, "top");
        }
      }
    }


  }

  submitForm(): void {
    if (this.isCheckRead === false) {
      this.appGlobalService.showToast('请先同意用户协议及隐私政策再继续使用APP', 2000, 'top');
      return;
    }
    if (this.loginForm.status === "INVALID") {
      this.getErrors();
      return;
    }
    this.disableBtn = true;
    this.loginForm.value.device_model = this.getDeviceModel();
    const obj = {
      account: this.loginForm.value.account,
      password: this.appGlobalService.encryptDes(this.loginForm.value.password),
      // isPreView: this.appGlobalService.isPreView,
      device_model: this.getDeviceModel()
    };

    // 2023.11.24 getUuid
    Object.assign(obj, { imei: this.eventService.getUuid(), clientType: this.appGlobalService.clientType });

    // 2024.09.19 huawei
    if (localStorage.getItem('huawei')) {
      Object.assign(obj, { amobile: 'huawei' });
    }

    // 蜂喔用户2.1.0 新增
    if (localStorage.getItem('wxloginOpenID')) {
      obj['openid'] = localStorage.getItem('wxloginOpenID');
    }
    if (localStorage.getItem("isDetailPage")) {
      obj['skip'] = 0;
    }
    const params = {
      content: obj,
      id: this.tagData.button.id,
      sessionId: localStorage.getItem("sessionId")
    };
    if (
      this.tagData.button.actionElement &&
      this.tagData.button.actionElement.param
    ) {
      this.tagData.button.actionElement.param.map(item => {
        params.content[item.name] = item.value;
      });
    }
    const that = this;
    this.http.post("application/submit", params, res => {
      if (res.success) {
        
        if (params.content.password && params.content.password.length > 0 ) {
          const alp = this.appGlobalService.encryptALP(params.content.password);
          localStorage.setItem('ALP', alp);
         }

        this.eventService.eventEmit.removeAllListeners("clearlistTagRefreshTime");
        if (res.data.position) {
          this.setPxwCityPosition(res.data.position);
        }
        if (res.data.user_id) {
          localStorage.setItem("userId", res.data.user_id);
          localStorage.setItem("loginAccount", this.loginForm.value.account);
          this.appGlobalService.initUmengEventWithParameters("enter_app_with_loginAccount_event");
          that.jPush
            .setAlias({
              sequence: 1,
              alias: this.appGlobalService.pushAlias + params.content.account
            })
            .then(
              result => {
                const sequence = result.sequence;
                const alias = result.alias;
                console.log("设置别名成功：" + alias);
              },
              error => {
                const sequence = error.sequence;
                const errorCode = error.code;
                console.log("设置别名失败：" + errorCode);
              }
            );

          this.http.get(
            "message/userinfo/im/" + res.data.user_id,
            response => {
              const data = response.data;
              if (res.data.user_id.includes('random')) {
                data.nickname = '访客';
              }
              if (data.nickname) {
                this.appGlobalService.currentNickName = data.nickname;
                localStorage.setItem('currentNickName', data.nickname);
              }
              if (data.avatar_url === null) { // 没头像给默认头像
                data.avatar_url = this.appGlobalService.defaultImg;
              }
              if (data.avatar_url) {
                this.appGlobalService.getBase64Str(data.avatar_url + "?x-oss-process=image/resize,h_36", str => {
                  localStorage.setItem('currentAvatarStr', str);
                  that.webSocketTalk.setAvatar(res.data.user_id, str);
                });
                this.appGlobalService.currentAvatarUrl = data.avatar_url;
                localStorage.setItem('currentAvatarUrl', data.avatar_url);
              }
              localStorage.setItem('currentWorkMobile', data.work_mobile);
              // 2024.08.02 联调接口返回参数
              if (res.data.shopGoodsCartCount) {
                // tslint:disable-next-line:no-string-literal
                data['shopGoodsCartCount'] = res.data.shopGoodsCartCount;
              }

              that.webSocketTalk.currentUserObj = data;

              this.indexedDBService.putByKeyCallbak(data, res.data.user_id, "user", () => {
                if (res.data.shopGoodsCartCount) {
                  that.webSocketTalk.setCartItemCount(res.data.shopGoodsCartCount);
                }
              });
            },
            error => {
              console.log("msg-----> error:" + JSON.stringify(error));
            }
          );
          // this.im.connectting(res.data.user_id);
          // 检测timer则需重新启动定时器
          // this.im.onStartMsgTimer();
          // this.connectting(res.data.user_id);
          // 检查 邀约消息列表和 消息详情表数据是否有变化
          // this.im.checkAndLoadChatData();

          // websocket链接
          this.webSocketTalk.connectting(this.loginForm.value.account, true, (eData) => {
            console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  ws.connectting   ', eData);
          });
          // this.webSocketTalk.checkAndLoadChatData();
          if (this.appGlobalService.clientType === 'pxw') {
            localStorage.setItem('startRefreshTimerTag', '1');
            this.eventService.eventEmit.emit("startRefreshTimer");
          }
        }

        // 登录成功后发现 alert 2s后跳转
        if (res.data.alert) {

          setTimeout(() => {
            const link = {
              params: res.data.alert.params,
              target: res.data.alert.target,
              type: 'pageModal'
            }
            this.pageModalService.openPage(link);
          }, 2000);
        }

        localStorage.setItem("loginStatus", "true");
        localStorage.setItem("needRefreshTab1", "true");
        localStorage.setItem("needRefreshTab2", "true");
        localStorage.setItem("needRefreshTab3", "true");
        localStorage.setItem("needRefreshTab4", "true");
        localStorage.setItem("needRefreshTab5", "true");

        if (that.isNeedGetBadgeAfterSubmit) {
          const tempParams = {
            id: this.tagData.badge,
            sessionId: localStorage.getItem("sessionId")
          }
          this.http.post("application/submit", tempParams, res => {
            if (res.success) {
              that.updateBadge(res.data.badge);
            }
          });
        } else {
          if (res.data && res.data.badge) {
            that.updateBadge(res.data.badge);
          }
        }


        if (localStorage.getItem("useTarget") === "true") {
          const cityId = JSON.parse(localStorage.getItem("position"))
            ? JSON.parse(localStorage.getItem("position")).code
            : 4403;
          const pageParams = {
            pageId: res.target,
            params: {
              code: cityId
            },
            sessionId: localStorage.getItem("sessionId")
          };
          this.appGlobalService.goToForward(pageParams);
          localStorage.removeItem("useTarget");
        } else {
          const skip = res.skip;
          if (skip && skip === 1) {
            // "是否跳转页面 0不跳/1跳"
            const pageParams = {
              pageId: res.target,
              params: res.params,
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          } else if (localStorage.getItem("isDetailPage") && skip === 0) {
            localStorage.setItem("needRefresh", "true");
            this.appGlobalService.popTarget();
            this.appGlobalService.goBack();
          } else if (skip === 0) {


            let tmpParams = res.params;
            if (localStorage.getItem('back_target') !== null) {
              tmpParams = params.content;
            }
            const pageParams = {
              pageId: res.target,
              params: tmpParams,
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          } else if (skip && skip === 4) { // 跳转到模态窗口
            // "是否跳转页面 0不跳/1跳"
            const link = {
              pageId: res.target,
              params: res.params,
              sessionId: localStorage.getItem("sessionId")
              , type: 'modal'
            };
            this.pageModalService.openPage(link);
          } else {
            localStorage.setItem("needRefresh", "true");
            this.appGlobalService.goBack();
          }
        }
      } else {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }
      this.disableBtn = false;
    });
  }
  editStyle() {
  }
  checkTime(i) {
    if (Number(i) < 10) {
      i = "0" + i;
    }
    return i;
  }
  async isYestday(theDate) {
    return (await new Date().getDate()) - theDate.getDate() === 1;
  }
  isSameWeek(old, now) {
    const oneDayTime = 1000 * 60 * 60 * 24;
    const oldCount = parseInt(old.getTime() / oneDayTime + "");
    const nowOther = parseInt(now.getTime() / oneDayTime + "");
    return (
      parseInt((oldCount + 4) / 7 + "") === parseInt((nowOther + 4) / 7 + "")
    );
  }
  getTime() {
    const m = parseInt(new Date().getMinutes() + "");
    return parseInt(new Date().getHours() + "") + ":" + (m < 10 ? "0" + m : m);
  }
  getDeviceModel() {
    return localStorage.getItem("device");
  }
  // 处理 员工 当前定位城市
  setPxwCityPosition(positionInfo) {
    if (this.appGlobalService.clientType === 'pxw') {
      // 如果有第一次城市信息，firstPostion === {}，存firstPostion
      const firstPostion = localStorage.getItem('firstPostion');
      if (!firstPostion) {
        localStorage.setItem('firstPostion', JSON.stringify(positionInfo));
        localStorage.setItem('position', JSON.stringify(positionInfo));
        // 通过城市名称设置经纬度
        this.mapBaiduService.getPointByName(positionInfo.name, (point) => {
          positionInfo.center = { lng: point.lng, lat: point.lat };
          localStorage.setItem('position', JSON.stringify(positionInfo));
        });
      }
    }
  }
  focusInput(type) {
    if (type === '1') {
      this.accountInput.setFocus();
    } else if (type === '2') {
      this.passwordInput.setFocus();
    }
  }
  async openArgument() {
    this.eventService.eventEmit.emit("openPage",
      // tslint:disable-next-line:no-string-literal
      JSON.stringify({ type: 'url', urlLinkTitle: "服务协议", target: window['appGlobalService'].serviceAgreementLink, params: {} }));
  }
  async alertPrivacyPolicy() {
    this.eventService.eventEmit.emit("openPage",
      // tslint:disable-next-line:no-string-literal
      JSON.stringify({ type: 'url', urlLinkTitle: "隐私权限", target: window['appGlobalService'].privatePolicyLink, params: {} }));
  }
  checkRead() {
    this.isCheckRead = !this.isCheckRead;
  }

  updateBadge(badge) {
    if (badge && badge.length > 0) {
      badge.forEach(element => {
        const key = Object.keys(element)[0];
        if (Number(element[key]) >= 0) {
          console.log("msg----->" + Number(element[key]));
          this.eventService.eventEmit.emit("firstBadgeForTab", {
            [key]: Number(element[key])
          });
        }
      });
    }
  }


  async closeModal() {
    const modal = await this.modalCtrl.getTop();
    if (modal !== undefined) {
      modal.dismiss({ form: null });
    }
  }


  goPage(link) {
    if (link && link.params && link.params.closeModalAfterShow) {
      this.closeModal();
    }
    this.pageModalService.openPage(link);
  }
  goPage1(link) {
    this.closeModal();
    this.pageModalService.openPage(link);
  }


  getVC(invalid) {
    console.log(this.registerForm.get("account"));
    if (invalid) {
      this.appGlobalService.showToast("请输入正确手机号码", 3000, "top");
    } else {
      const params = {
        content: {
          mobile: this.registerForm.value.account
        },
        id: this.tagData.codeButton["submit"]["id"],
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post("application/submit", params, data => {
        if (data.success) {
          this.appGlobalService.showToast(
            "验证码已发送、请注意查收",
            3000,
            "top"
          );
          if (data.data) {
            this.mvcode = data.data.mvcode;
          }
          this.time = 90;
          const timer = setInterval(() => {
            this.time = this.time - 1;
            if (this.time === -1) {
              clearInterval(timer);
              this.text = "获取验证码";
            }
          }, 1000);
        } else {
          this.appGlobalService.showToast(data.message, 3000, "top");
        }
      });
    }
  }


  // 一键登录页面点击其他手机号码登录
  submit(type?) {
    if (this.isCheckRead === false) {
      this.appGlobalService.showToast('请先同意用户协议及隐私政策再继续使用APP', 2000, 'top');
      return;
    }
    if (type !== undefined) {
      if (this.registerForm2.status === "INVALID") {
        this.getErrors();
        return;
      }
    } else {
      if (this.registerForm.status === "INVALID") {
        this.getErrors();
        return;
      }
    }

    // else if (this.passwordNum1 !== this.passwordNum) {
    //   this.appGlobalService.showToast("两次输入的密码不一致", 3000, "top");
    //   return;
    // }


    // 禁止用户重复提交
    this.disableBtn = true;
    const param = {
      content: Object.assign(type !== undefined ? this.registerForm2.value : this.registerForm.value),
      id: this.tagData.button.id,
      sessionId: this.sessionId
    };

    let mobileVcCodePageTarget;
    if (type !== undefined) {
      param.content.password = this.appGlobalService.encryptDes(this.registerForm2.value.password)
    }
    if (localStorage.getItem('wxloginOpenID')) {
      param.content['openid'] = localStorage.getItem('wxloginOpenID');
    }
    this.tagData.button.actionElement.param.map(item => {
      param.content[item.name] = item.value;
      if (param.content['page_name'] !== undefined && item.name === 'page_name') {
        mobileVcCodePageTarget = item.value;

      }
    });

    // 重新赋值
    // param.content.password = this.appGlobalService.encryptDes(this.passwordNum);
    // param.content.password1 = this.appGlobalService.encryptDes(this.passwordNum1);
    // 用户注册城市
    // param.content.city_id = JSON.parse(this.mapBaiduService.getStore("position")).code;
    this.http.post("application/submit", param, data => {
      if (data.success) {
        if (mobileVcCodePageTarget && mobileVcCodePageTarget > 0) {
          data.target = mobileVcCodePageTarget;
        }
        this.processLoginData.processLoginData(data, type !== undefined ? this.registerForm2.value.account : this.registerForm.value.account, param)
        if (param.content.password && param.content.password.length > 0 ) {
         const alp = this.appGlobalService.encryptALP(param.content.password)
         localStorage.setItem('ALP',alp); 
        }
      } else {
        this.appGlobalService.showToast(data.message, 3000, "top");
      }
      this.disableBtn = false;
    });
  }


  goBack() {

  }


  wxAuth() {
    this.pageModalService.wxAuth(this.tagData);
  }

}

